<?php
/**
 * [Description] 云保单
 * @author [yhy]<[Time:2017/08/14]>
 */
class YunBaoDanAction extends IndexAction{
    //用户列表分业每页长度
    const LIMITILENGTH = 10;
    //家庭列表显示每页长度
    const LIMITIFAMILYENGTH = 5;
    //家庭（被保人）保单列表每页显示长度
    const DEFAULTLENGTH = 5;
     // 保单解析状态显示数量
    const LIMITPOLICYSTATUS = 10;
    //家庭保单分析每页长度
    const LIMITFAMILYLENGTH = 5;
    //缩略图宽度
    const THUMB_WIDTH = 69;
    //缩略图高度
    const THUMB_HEIGHT = 91;
    // 附件上传大小(单位：M)
    const IMG_MAXSIZE = 8;
    //保单详情分页长度
	//  附件上传类型
    private $img_exts = array('jpg', 'pjpeg', 'gif', 'png', 'jpeg');
	//倒入公用类
    public function __construct(){
        parent::__construct();
        import('Common.Communication.Communication',APP_PATH, '.php');
        import('Common.PublicMethod.PublicMethod', APP_PATH, '.php');
         //  导入redis类
        import('Common.Tool.useRedis',APP_PATH,'.php');
        //  认证登陆
        $this -> certifiedLanding();
        $this -> assign('version',self::VERSION);
    }

    //上传保单页面
    public function uploadPolicyImg(){
        //获取用户加密后的uid
        $encryptUid = I('encryptUid', '' ,'htmlspecialchars,trim');
        //  错信息获取(如果有)
        $errormsg = I('errormsg', '', 'htmlspecialchars,trim');
        $this->assign('errormsg',$errormsg);
        $this->assign('clientUid',$encryptUid);
        //  图片大小js处理
        $this->assign('picSize',self::IMG_MAXSIZE*1024*1024);
        $this -> display(__FUNCTION__);
    }


    //  保单上传(用于form表单提交)
    public function policyUpload()
    {
        //  图片多于两张并且创建文件夹
        $this->morethanPics();
        //  获取到客户UID
        $clientUid = I('clientUid', '' ,'htmlspecialchars,trim');
        if(!$clientUid)
        {
            // $this->errorMessage('必须传入客户ID!');
            $this -> jsonResponse(array('status' => 6, 'msg' => '必须传入客户ID!'));
        }
        //  解密后客户的uid
        $DeClientUid = $this->userIdDecrypt($clientUid);
        //  代理人uid(未加密)
        $deAgentUid = $this->getUid();
        //  加密代理人UID
        $encyptArr = PublicMethod::numberBetweenEncrypt(0, $deAgentUid);
        $agentUid = implode('_', $encyptArr);
        //  原图信息
        $picInfo = array();

        $img64basePost = I('img64base', '' ,'htmlspecialchars,trim');
        //  将base64图片解密
        foreach($img64basePost as $k=>$v){
            if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $v, $result)){
                //  type为获取到图片的类型
                $type = $result[2];
                if(!in_array($type, $this->img_exts))
                {
                    // $this->errorMessage('上传文件类型错误');
                    $this -> jsonResponse(array('status' => 5, 'msg' => '上传文件类型错误!'));
                }
                $name=PublicMethod::randomString(32);  //生成一个32位随机数图片名字
                $new_file = C('POLICY.policyOriginal')."{$name}.{$type}"; //  新图片存放位置
                $keyName = $name.'.'.$type;
                if(file_put_contents($new_file, base64_decode(str_replace($result[1], '', $v))))
                {
                    //  新图片存放位置集合
                    $picInfo[$keyName] = $new_file;
                }else
                {
                    $this -> jsonResponse(array('status' => 4, 'msg' => '图片无法转移成功!'));
                    //  用于调试展示出的信息
                    // $this->errorMessage('图片无法转移成功!');
                }
            }else
            {
                    $this -> jsonResponse(array('status' => 3, 'msg' => '上传文件类型不可识别!'));
                    // $this->errorMessage('上传文件类型不可识别');
            }
        }
        //  设置缩略图需要的最大宽高(也是自定义的宽度和高度)
        $max_width = self::THUMB_WIDTH;
        $max_height = self::THUMB_HEIGHT;
        //  保单图片链接地址
        $imagesUrl = array();
        // 保单图片缩略图链接地址
        $imagesUrlThumb = array();
        //  循环获取到接口需要的图片地址和缩略图地址
        foreach($picInfo as $key => $val)
        {
            //  原图地址(包含文件名称)
            $policImg = $val;
            //  缩略图处理
            $img_path_thumb = C('POLICY.policyThumb').$key;
            //  引入缩略图生成类
            import("ORG.Util.Image");
            $Img = new Image(); //  实例化图片类对象
            //  生成缩略图
            $flag = $Img::thumb2($policImg,$img_path_thumb,'',$max_width,$max_height);
            //  如果缩略图没有生成出来返回并且记录日志
            if(!$flag)
            {
                // $errorMsg = '缩略图生成有误';
                //  跳转回上传页面
                // $this -> errorMessage($errorMsg);
                $this -> jsonResponse(array('status' => 2, 'msg' => '缩略图生成有误!'));
            }
            //  代码执行到此，数据库中的图片数据会和存储的图片相对应
            //  原图地址
            $imagesUrl[] =  $this->imgPath($policImg);
            //  缩略图地址
            $imagesUrlThumb[] =  $this->imgPath($img_path_thumb);
         }

        //  保存图片
        //  随机生成32位字符串
        $randomString = PublicMethod::unique();
        //  当前时间戳
        $timestamp = time();
        //  获取平台channelkey
        $channelKey = C('POLICY.channelkey');
        //  获取平台账号
        $account = C('POLICY.account');
        //  校验key
        $key = PublicMethod::produceCheckKey($randomString,$timestamp,$channelKey);
        //  回调处理函数
        $callBackUrl = URL_JUNKANG . '/PolicyCallback/callbackPolicyData/clientUid/'.$clientUid.'/agentUid/'.$agentUid;
        $defaultChannel = C('POLICY.defaultChannel');
        $qudaoAccount = $defaultChannel[1];
        //  渠道id
        $baoshitongChannelId = $this->getChannelId($qudaoAccount);
        if(!$baoshitongChannelId){
             // $this -> errorMessage('根据渠道账号获取渠道id失败!');
                $this -> jsonResponse(array('status' => 20, 'msg' => '根据渠道账号获取渠道id失败!'));
        }
        //  处理返回的保单信息
        $response = $this -> getUserInfo($deAgentUid);
        if (!$response) {
            // $this -> errorMessage('ServerError -> 获取代理人信息失败！）');
               $this -> jsonResponse(array('status' => 19, 'msg' => '获取代理人信息失败！'));
        }
        if(!$response['userName']){
            // $this -> errorMessage('ServerError -> 获取代理人名字失败！）');
               $this -> jsonResponse(array('status' => 18, 'msg' => '获取代理人名字失败！'));
        }
        //  代理人的用户名
        $userName = $response['userName'];
        //整合请求数据
        $requestData = array(
            'account' => $account,  //  平台账号
            'otherType' => 5,  //  账号类型
            'imagesUrl' => $imagesUrl,  //  图片信息
            'imagesUrlThumb' => $imagesUrlThumb,  //  缩略图信息
            'randomString' => $randomString,  //  唯一的随机字符串(32位,如bb18279b3cb1f7fa0d9c725f46f58042)
            'timestamp'  => $timestamp,  //  时间戳
            'key' => $key,  //  校验Key
            'userName' => $userName,  //  用户账号
            //是否回调
            'isCallBack' => 1,
            //是否返回数据
            'isReturnPolicyInfo' => 1,
            //返回数据的回调链接
            'callBackUrl' => $callBackUrl,
            'baoshitongChannelId' => $baoshitongChannelId,
            //客户uid
            'clientUid'=>$DeClientUid,
        );
        //上传保单
        $response = Communication::request('policyApi', '/Api/PolicyProduct/getPolicyProductInfo', $requestData);
        if ($response['status'] != 1) {
            // $this -> errorMessage('保单图片解析失败' . $response['status']);
            $this -> jsonResponse(array('status' => 17, 'msg' => '保单图片解析失败'));                 
        }
        //获取平台id
        $baoshitongPlatformId = $this -> getPlatformId($account);

        //  生成checkkey算法
        $quChannelKey = $defaultChannel[0];
        $channel = $defaultChannel[2];
        $checkKey = md5(md5(sha1($qudaoAccount . $channel . $quChannelKey) . $quChannelKey));
        //  添加保单图片上传记录
        $this->addImageRecord($deAgentUid,$imagesUrl, $key,$baoshitongPlatformId,$checkKey);
        //添加用户保单上传记录
        $requestData = array(
            'uid'       =>  $deAgentUid,
            'imagesUrl' =>  $imagesUrl,
            'key'       =>  $key,
            'baoshitongPlatformId' => $baoshitongPlatformId,
            'baoshitongChannelId'  => $baoshitongChannelId,
        );
        $response = Communication::request('api', '/Api/BaoShiTong/addUserUploadRecord', $requestData);
        if($response['status'] != 1)
        {
            // $this -> errorMessage('添加用户保单上传记录失败');     
            $this -> jsonResponse(array('status' => 16, 'msg' => '添加用户保单上传记录失败'));              
        }
        //  添加保单图片上传记录
        $this->policyParsingRecord($deAgentUid, $key,$baoshitongPlatformId,$checkKey);

        //  获取客户的username用于发送模板消息(上传保单)
        $response = $this -> getUserInfo($DeClientUid);
        if (!$response) {
            // $this -> errorMessage('ServerError -> 获取客户信息失败！）');
            $this -> jsonResponse(array('status' => 15, 'msg' => '获取客户信息失败！'));              
        }
        if(!$response['userName']){
            // $this -> errorMessage('ServerError -> 获取客户名字失败！）');
            $this -> jsonResponse(array('status' => 14, 'msg' => '获取客户名字失败！'));                
        }

        //  客户的用户名
        $userName = $response['userName'];    
        //  发送模版消息所需要数据
        $messageData = array('userName' => $userName);
        $requestData = array('uid' => $deAgentUid, 'messageTemplateId' => 4,'messageData'=>$messageData);
        //  发送模板消息接口
        $response = Communication::request('enterpriseApi', '/Api/JunKangEnterprise/addMessageTemplateInfo', $requestData);
        if ($response['status'] != 1)
        {
            PublicMethod::log(__FUNCTION__, '添加用户消息通知失败');
        }  
        //  图片上传成功后页面跳转
        // $this->gotoUrl(APP_NAME.'/YunBaoDan/policyAnalysisStatus');
        $this -> jsonResponse(array('status' => 1, 'msg' => '保单上传成功'));  
    }

    //用户个人中心（添加新用户）
    public function personalCenter(){
        //获取uid
        $uid = $this -> getUid();
        //获取用户信息
        $userInfo = $this -> getUserInfo($uid);
        if(!$userInfo){
            $this -> debug('ServerError -> 获取客户信息失败(用户)');
        }
        if(empty($userInfo['userName'])){
            $this -> debug('ServerError -> 获取客户姓名失败(用户)');
        }
        //获取用户头像
        $userPortraint = $this -> getUserPortraint($uid, $userInfo['userPortrait']);
        $userName = $userInfo['userName'];
        //获取推送消息
        $shortMessage = $this -> getShortMessageList($uid);
        if(!$shortMessage){
            $this -> debug('ServerError -> 获取模版信息失败');
        }
        if(empty($shortMessage['info'])){
            //获取模版消息失败(或者为空)
            $this -> assign('noMessage',1);
        }
        $enAgentUidArr = PublicMethod::numberBetweenEncrypt(0, $uid);
        $enAgentUid= implode('_', $enAgentUidArr);
        //加密agentUid
        $this->assign('enAgentUid', $enAgentUid);
        //分配用户名
        $this -> assign('userName', $userName);
        // 分配用户头像
        $this -> assign('userPortraint', $userPortraint);
        //分配模版消息
        $this -> assign('shortMessage', $shortMessage['info']);
        $this -> display(__FUNCTION__);
    }



    //客户详情列表
    public function familyPolicy(){
        // //获取用户加密后的uid
        $encryptUid = I('encryptUid', '' ,'htmlspecialchars,trim');
        $clientUid = $this -> userIdDecrypt($encryptUid);
        // 获取用户信息
        $clientInfo = $this -> getUserInfo($clientUid);
        if(!$clientInfo){
            $this -> bebug('ServerError -> 获取客户信息失败(客户)');
        }
        if(empty($clientInfo['userName'])){
            $this -> bebug('ServerError -> 获取客户姓名失败（客户）');
        }
        $clientName = isset($clientInfo['userName']) ? $clientInfo['userName'] : '';
        //获取家庭保单数据
        $policyInfo = $this -> getFamilyPolicyInfo($clientUid);
        if(!$policyInfo){
            $this -> debug('ServerError -> 无法获取客户保单信息' );
        }
        //定义保单信息
        $policyCon = array();
        $policyCon['payYear'] = isset($policyInfo['payYear']) ? substr(($policyInfo['payYear']/10000) ,0,6) : 0;
        $policyCon['payMonth'] = isset($policyInfo['month']) ? substr(($policyInfo['month']/10000), 0, 6) : 0;
        $policyCon['validPolicy'] = isset($policyInfo['validPolicy']) ? $policyInfo['validPolicy'] : 0;
        $policyCon['invalisPolicy'] = isset($policyInfo['invalisPolicy']) ? $policyInfo['invalisPolicy'] : 0;
        //获取页码
        $pageNow = I('p', 1, 'htmlspecialchars,trim');
        //定义每夜显示长度
        $limitLength = self::LIMITIFAMILYENGTH;
        //定义开始
        $limitStart = ($pageNow -1) * $limitLength;
        //获取agnetUid
        $uid = $this -> getUid();
        //请求接口数据
        $requestData = array('clientUid' => $clientUid, 'uid' => $uid,'limitStart' => $limitStart, 'limitLength' => $limitLength);
        //获取家庭保单详情
        $familyPolicyList = $this -> getFamilyPolicyList($requestData);
        if ($familyPolicyList['status'] != 1 || empty($familyPolicyList['info']['info'])) {
            $this -> debug('ServerError -> 无法获取客户家庭保单详情' . $familyPolicyList['status']);
        }
        //获取总条数
        $policyCount = isset($familyPolicyList['info']['count']) ? $familyPolicyList['info']['count']: 0;
        //加密被保人uid
        foreach ($familyPolicyList['info']['info'] as &$familyPolicy) {
            $encyptArr = PublicMethod::numberBetweenEncrypt(0, $familyPolicy['contactsId']);
            $familyPolicy['contactsId'] = implode('_', $encyptArr);
        }
        //获取代理人uid
        $agentUidArr = PublicMethod::numberBetweenEncrypt(0, $uid);
        $agentUid = implode('_', $agentUidArr);
        //分页
        $pageShow = $this -> getPages($policyCount,$limitLength);
        //分配代理人id
        $this -> assign('agentUid', $agentUid);
        //分配分业
        $this -> assign('pageShow', $pageShow);
        //分配用户名
        $this -> assign('clientName', $clientName);
        // 分配被保人数量
        $this -> assign('policyCount', $policyCount);
        //分配保单信息
        $this -> assign('familyPolicyList', $familyPolicyList['info']['info']);
        //分配加密uid
        $this -> assign('encryptUid', $encryptUid);
        //分配保单信息数据
        $this -> assign('policyInfo', $policyCon);
        $this -> display(__FUNCTION__);
    }

    //展示用户列表(有保单)
    public function usersListHasPolicy(){
       //获取代理人uid
        $agentUid = $this -> getUid();
        if (!$agentUid) {
            $this -> debug('ServerError ->获取代理人uid失败(有保单)！');
        }
        //获取页码
        $pageNow = I('p', 1, 'htmlspecialchars,trim');
        //定义每夜显示长度
        $limitLength = self::LIMITILENGTH;
        //定义开始
        $limitStart = ($pageNow -1) * $limitLength;
        $requestData = array('uid' => $agentUid, 'limitStart'=> $limitStart, 'limitLength' => $limitLength);
        $userInfo = $this -> getUserListHasPolicy($requestData);
        //无保单的用户不存在时展示无保单页面
        if(!$userInfo['count']){
            $this -> assign('isUser', true);
        }
        //获取分页数据
        $pageShow = $this->getPages($userInfo['count'],$limitLength);
        //uid加密(0和uid)
        foreach ($userInfo['info'] as $key => &$userContent) {
            $encyptArr = PublicMethod::numberBetweenEncrypt(0, $userContent['clientUid']);
            $userContent['clientUid'] = implode('_', $encyptArr);
        }
        //分配分业信息
        $this -> assign('pageShow', $pageShow);
        $this -> assign('userInfo', $userInfo['info']);
        $this -> display(__FUNCTION__);
    }

     //展示用户列表（无保单）
    public function usersListNoPolicy(){
       //获取代理人uid
        $agentUid = $this -> getUid();
        if (!$agentUid) {
            $this -> debug('ServerError -> 获取代理人uid失败(无保单)！');
        }
        $userInfo = $this -> getUserListNoPolicy($agentUid);
        //无保单的用户不存在时`
        if(!$userInfo['count']){
            $this -> assign('isUser', true);
        }
        //uid加密(0和uid)
        foreach ($userInfo['info'] as $key => &$userContent) {
            $encyptArr = PublicMethod::numberBetweenEncrypt(0, $userContent['clientUid']);
            $userContent['clientUid'] = implode('_', $encyptArr);
        }
        $this -> assign('userInfo', $userInfo['info']);
        $this -> display(__FUNCTION__);
    }


    //如何拍保单
    public function photoGraph(){
        $this -> display(__FUNCTION__);
    }


    //保单解析进度
    public function policyAnalysisStatus(){

        // 获取uid
        $uid = $this -> getUid();
        //获取用户信息
        $userInfo = $this -> getUserInfo($uid);
        if(!$userInfo){
            $this -> debug('ServerError -> 获取解析进度用户信息失败！');
        }
        if(empty($userInfo['userName'])){
            $this -> debug('ServerError -> 获取解析进度用户姓名失败！');
        }
        // 获取用户头像
        $userPortraint = $this -> getUserPortraint($uid, $userInfo['userPortrait']);
        //获取页码
        $pageNow = I('p', 1, 'htmlspecialchars,trim');
        //定义每夜显示长度
        $limitLength = self::LIMITPOLICYSTATUS;
        //定义开始
        $limitStart = ($pageNow -1) * $limitLength;
        $requestData = array('uid' => $uid, 'limitStart' => $limitStart, 'limitLength' => $limitLength);
        $policyAnalysisStatus = $this -> getPolicyStatus($requestData);
        if(!$policyAnalysisStatus){
            $this -> debug('ServerError -> 获取保单解析状态失败！');
        }
        //如果数据为空
        if(empty($policyAnalysisStatus['policyInfo'])){
            $this -> display('noPolicyAnalysisStatus');
            return false;
        }
        //定义存放保单信息的数组
        $policyAnnlysisInfo = array();
        //获取编号
        $startNum = ($pageNow-1) * $limitLength + 1;
        //获取保单解析状态
        foreach ($policyAnalysisStatus['policyInfo'] as $policyAnalysis) {
            //定义存保单解析放数据的容器
            $policyContent = '';
            //获取保单解析状态码
            $policyContent['surviveStatus'] = $policyAnalysis['surviveStatus'];
            //问题描述
            $policyContent['ProblemDiscription'] = isset($policyAnalysis['ProblemDiscription']) ? $policyAnalysis['ProblemDiscription']: '' ;
            $policyContent['startNum'] = $startNum;
            $startNum ++;
            //保单上传时间
            $policyContent['addTime'] = $policyAnalysis['addTime'];
            // 上传的保单图片
            if(!$policyAnalysis['imageIndexInfo']){
                PublicMethod::log(__FUNCTION__, '获取保单号失败');
            }
            $policImgs = $this -> getImgUrl($policyAnalysis['imageIndexInfo']);

            if(!$policImgs){
                PublicMethod::log(__FUNCTION__, '获取图片路径失败');
            }
            // 获取图片路径
            $policyContent['policyImages'] = $policImgs;
            $policyAnnlysisInfo[] = $policyContent;
        }

        //获取总条数
        $policyCount = isset($policyAnalysisStatus['count']) ? $policyAnalysisStatus['count'] : 0;
        $pageShow = $this->getPages($policyCount,$limitLength);
        //获取用户名
        $userName = $userInfo['userName'];
        // 分配用户名
        $this -> assign('userName', $userName);
        //分配用户头像
        $this -> assign('userPortraint', $userPortraint);
        //分配分页
        $this -> assign('pageShow',$pageShow);
        // 分配保单解析数据
        $this -> assign('policyInfo', $policyAnnlysisInfo);
        $this -> display(__FUNCTION__);
    }

    //个人保单分析（柱状图）
    public function personalPolicyAnalysis(){
        $projectLiabilityInfo = $this -> getProjectLiabilityInfo();
        if($projectLiabilityInfo['status'] != 1){
            $this -> debug($projectLiabilityInfo['msg']);
        }
        //获取加密uid
        $encryptUid = I('encryptUid', '', 'htmlspecialchars,trim');
        $clientUid = $this->userIdDecrypt($encryptUid);
        // 获取被保人uid
        $encryptContactsId = I('encryptContactsId', '', 'htmlspecialchars,trim');
        $contactsId = $this->userIdDecrypt($encryptContactsId);
        $contactsInfo = $this -> getContactsInfo($contactsId);
        if(!$contactsInfo){
            $this -> debug('ServerError -> 获取被保人保信息失败！');
        }
        if(empty($contactsInfo['userName'])){
            $this -> debug('ServerError -> 获取被保人保姓名失败！');
        }
        $contactsUserName =  $contactsInfo['userName'];
        //获取保单号
        $contactsPolicyIds = $this -> getInsuredPolicyNumber($contactsId, $clientUid);
        if(!$contactsPolicyIds){
            $this -> debug('ServerError -> 获取保单号信息失败!');
        }
        //保险项目
        $policyInfo = $this -> getPolicyInfoById($contactsPolicyIds);
        if($policyInfo['status'] != 1){
            $this -> debug('ServerError ->' . $policyInfo['msg']);
        }
        $policyInfo = array('CurrencyType' => 0, 'Liabilitys' => $policyInfo['info']);
        $policyContent = json_encode($policyInfo);
        // 责任关系
        $this -> assign('projectLiabilityInfo', $projectLiabilityInfo['info']);
        //保单详情
        $this -> assign('policyContent', $policyContent);
        //用户名
        $this -> assign('userName', $contactsUserName);
        //通过保单号获取保单信息
        $this -> display(__FUNCTION__);
    }

    //获取被保人保单号
    public function getInsuredPolicyNumber($contactsId, $clientUid){
        $uid = $this -> getUid();
        $requestData = array('uid' => $uid, 'clientUid' => $clientUid, 'contactsId' => $contactsId);
        $response = Communication::request('enterpriseApi', '/Api/JunKangEnterprise/getInsuredPolicyNumber', $requestData);
        if(!$response){
            PublicMethod::log(__FUNCTION__, '获取保单号信息失败' . $response);
        }
        return $response['info'];
    }

    //通过保单号获取保单信息
    private function getPolicyInfoById($policyIds){
        array_unique($policyIds);
        //要查询的字段
        $queryField = array('Liabilitys.shortName', 'Liabilitys.SecurityMoney', 'CurrencyType');
        $communicationKey = C('POLICY.communicationKey');
        if(!$communicationKey){
            return array('status' => 2, 'msg' => '获取communicationKey失败');
        }
        $requestData = array('queryField' => $queryField, 'communicationKey' => $communicationKey, 'policyIdList' => $policyIds);
        $policyContent = Communication::request('sourcePolicy', '/Api/Policy/queryAllPolicyInfo', $requestData);

        if($policyContent['status'] != 1){
            return array('status' => 3, 'msg' => '获取保单信息失败！' . $policyContent['status']);
        }
        if(empty($policyContent['info'])){
            return array('status' => 4, 'msg' => '获取保单信息(mongo)不存在！');
        }
        //存放保单数据的数组
        $policyCont = array();
        //获取汇率
        $exchange = C('goldExchange.RMBExchangeDollar');
        foreach ($policyContent['info'] as $policyInfo) {
            $policy = $policyInfo['Mongo_data'];
            foreach ($policy['Liabilitys'] as &$policyCon) {
                $policyMoney = ($policy['CurrencyType'] == 1) ? ($policyCon['SecurityMoney'] * $exchange) : $policyCon['SecurityMoney'];
                $policyCon['SecurityMoney'] =  floor($policyMoney *100)/100;
            }
            $responsibility = &$policy['Liabilitys'];
            if(!$responsibility){
                continue;
            }
            //定义存放统一数据格式的空数组
            $liabilitys = array();
            //数据整合（返回一条数据是一维数组返回多条数据时是二维数组）
            //合并一维数组
            if (isset($responsibility['Pid'])) {
                $liabilitys[] = $responsibility;
            }else {
                //整合二维数组
                $liabilitys = $responsibility;
            }
            $policyCont = array_merge($policyCont,$liabilitys);
        }
        $policyCont = $this->consolidationResponsibility($policyCont);
        return  array('status' => 1, 'msg' => '通过保单号获取保单信息成功', 'info' => $policyCont);
    }

    //家庭保单详情列表（带小图标）
    public function familyPolicyList(){
        // 获取代理人uid
        $uid = $this -> getUid();
        //获取加密uid
        $encryptUid = I('encryptUid', '', 'htmlspecialchars,trim');
        $clientUid = $this->userIdDecrypt($encryptUid);
        //获取用户信息
        $clientInfo = $this -> getUserInfo($clientUid);
        if(!$clientInfo){
            $this -> debug('ServerError -> 无法获取客户信息!' );
        }
         if(empty($clientInfo['userName'])){
            $this -> debug('ServerError -> 获取客户姓名失败！' );
        }
        $userName = $clientInfo['userName'];
        $policyInf = $this -> getFamilyPolicyInfo($clientUid);
        if(!$policyInf){
            $this -> debug('ServerError -> 获取客户保单信息失败' );
        }
        //定义保单信息
        $policyCon = array();
        $policyCon['payYear'] = isset($policyInf['payYear']) ? substr(($policyInf['payYear']/10000) ,0,6)  : 0;
        $policyCon['payMonth'] = isset($policyInf['month']) ? substr(($policyInf['month']/10000) ,0,6) : 0;
        $policyCon['validPolicy'] = isset($policyInf['validPolicy']) ? $policyInf['validPolicy'] : 0;
        $policyCon['invalisPolicy'] = isset($policyInf['invalisPolicy']) ? $policyInf['invalisPolicy'] : 0;
        //获取页码
        $pageNow = I('p', 1, 'htmlspecialchars,trim');
        //定义每夜显示长度
        $limitLength = self::DEFAULTLENGTH;
        //定义开始
        $limitStart = ($pageNow -1) * $limitLength;
        $requestData = array('uid' => $uid, 'clientUid' => $clientUid, 'limitLength' => $limitLength, 'limitStart' => $limitStart);
        $policyInfo = $this -> getClientPolicyInfo($requestData);
        if ($policyInfo['status'] != 1 || empty($policyInfo['info']['info'])) {
            $this -> debug('ServerError -> 获取家庭保单详情失败！' . $policyInfo['status']);
        }
        //获取保单号
        $policyIds = $policyInfo['info']['info'] ? $policyInfo['info']['info'] : '';
        if(!$policyIds){
            $this -> debug('ServerError ->  获取保单号失败！');
        }
        //获取家庭保单的信息
        $policyContent = $this -> getPolicyContent($policyIds);
        if ($policyContent['status'] != 1) {
            $this -> debug('ServerError -> ' . $policyContent['msg']);
        }
        //获取总数
        $policyIdsCount = $policyInfo['info']['count'] ? $policyInfo['info']['count'] : 0;
        //分页
        $pageShow = $this -> getPages($policyIdsCount,$limitLength);
        $policyCount = I('policyCount', 0, 'htmlspecialchars,trim');
        //分配加密agentUid
        $enAgentUidArr = PublicMethod::numberBetweenEncrypt(0, $uid);
        $enAgentUid= implode('_', $enAgentUidArr);
        $this->assign('enAgentUid', $enAgentUid);
        //分配保单信息
        $this -> assign('policyContent', $policyContent['info']);
        //分页
        $this -> assign('pageShow', $pageShow);
        //分配被保人数
        $this -> assign('policyCount', $policyCount);
        //分配保单数据
        $this -> assign('policyInf', $policyCon);
        //加密用户id
        $this -> assign('encryptUid', $encryptUid);
        //分配用户名
        $this -> assign('userName', $userName);
        $this -> display(__FUNCTION__);
    }


    // //客户保单详情（带小图标）
    // public function personalPolicyList(){
    //     //获取用户加密后的uid
    //     $encryptUid = I('encryptUid', '' ,'htmlspecialchars,trim');
    //     //获取受保人uid
    //     $encryptContactsId = I('encryptContactsId', '' ,'htmlspecialchars,trim');
    //     //获取客户uid
    //     $clientUid = $this -> userIdDecrypt($encryptUid);
    //     //获取被保人uid
    //     $contactsId = $this -> userIdDecrypt($encryptContactsId);
    //     //解析被保人保单信息
    //     $analysisInfo = $this -> getAnalysisInfo($clientUid, $contactsId);
    //     if(!$analysisInfo){
    //         $this -> debug('ServerError -> 获取被保人保单信息失败!');
    //     }
    //     //定义保单信息数组
    //     $policyInfo = array();
    //     $policyInfo['payYear'] = isset($analysisInfo['payYear']) ? substr(($analysisInfo['payYear']/10000) ,0,6)  : 0;
    //     $policyInfo['payMonth'] = isset($analysisInfo['month']) ? substr(($analysisInfo['month']/10000) ,0,6) :0;
    //     $policyInfo['validPolicy'] = isset($analysisInfo['validPolicy']) ? $analysisInfo['validPolicy'] : 0;
    //     $policyInfo['invalisPolicy'] = isset($analysisInfo['invalisPolicy']) ? $analysisInfo['invalisPolicy'] : 0;
    //     //获取被保人信息
    //     $contactsInfo = $this -> getContactsInfo($contactsId);
    //     if(!$contactsInfo){
    //         $this -> debug('ServerError -> 获取被保人保信息失败！');
    //     }
    //     if(empty($contactsInfo['userName'])){
    //         $this -> debug('ServerError -> 获取被保人保姓名失败！');
    //     }
    //     $contactsUserName =  $contactsInfo['userName'];
    //     //获取客户uid
    //     $clientUid = $this -> userIdDecrypt($encryptUid);
    //     $uid = $this -> getUid();
    //     //获取页码
    //     $pageNow = I('p', 1, 'htmlspecialchars,trim');
    //     //定义每夜显示长度
    //     $limitLength = self::DEFAULTLENGTH;
    //     //定义开始
    //     $limitStart = ($pageNow -1) * $limitLength;
    //     //请求数据
    //     $requestData = array('uid' => $uid, 'clientUid' => $clientUid, 'contactsId' => $contactsId, 'limitStart' => $limitStart, 'limitLength' => $limitLength);
    //     //获取保单号信息
    //     $contactsIdPolicyInfo = $this -> getContactsIdPolicyInfo($requestData);
    //     if($contactsIdPolicyInfo['status'] != 1 || empty($contactsIdPolicyInfo['info']['info'])){
    //         $this -> debug('ServerError -> 获取被保人保单详情失败！');
    //     }
    //     //获取总数
    //     $policyIdsCount = $contactsIdPolicyInfo['info']['count'] ? $contactsIdPolicyInfo['info']['count'] : 0;
    //     //分页
    //     $pageShow = $this -> getPages($policyIdsCount,$limitLength);
    //     //  获取用户保单列表信息
    //     $policyContent = $this -> getPolicyContent($contactsIdPolicyInfo['info']['info']);
    //     if ($policyContent['status'] != 1) {
    //         $this -> debug('ServerError -> ' . $policyContent['msg']);
    //     }
    //     //分配保单数据
    //     $this -> assign('policyInf', $policyInfo);
    //     //分配被保人姓名
    //     $this -> assign('contactsUserName', $contactsUserName);
    //     //分配保单信息
    //     $this -> assign('policyContent', $policyContent['info']);
    //     //分页
    //     $this -> assign('pageShow', $pageShow);
    //     //分配被保人id
    //     $this -> assign('encryptContactsId', $encryptContactsId);
    //     $this -> assign('encryptUid', $encryptUid);
    //     $this -> display(__FUNCTION__);
    // }
    //家庭保单详情（柱状图）
    public function familyPolicyAnalysis(){
        //获取页码
        $pageNow = I('p', 1, 'htmlspecialchars,trim');
        //定义每夜显示长度
        $limitLength = self::LIMITFAMILYLENGTH;
        //定义开始
        $agentUid = $this -> getUid();
        $limitStart = ($pageNow -1) * $limitLength;
        //获取所拥有这张保单代理人uid
        $clientUid = I('encryptUid', '' ,'htmlspecialchars,trim');
        $clientUid = $this -> userIdDecrypt($clientUid);
        $requestData = array('uid' => $agentUid, 'clientUid' => $clientUid, 'limitStart'=> $limitStart, 'limitLength' => $limitLength);
        $familyPolicyList = $this -> getFamilyPolicyList($requestData);
        if ($familyPolicyList['status'] != 1 || empty($familyPolicyList['info']['info'])) {
            $this -> debug('ServerError -> 获取客户家庭保单详情失败' . $familyPolicyList['status']);
        }
         if(!$familyPolicyList['info']['count']){
            $this -> assign('isUser', true);
            return;
        }
        // 定义保单信息容器
        $familyPolicyInfo = array();
        foreach ($familyPolicyList['info']['info'] as $familyPolicy) {
            // 定义临时数组
            $policyContent = array();
            //获取被保人的保单列表
            $contactsPolicyIds = $this -> getInsuredPolicyNumber($familyPolicy['contactsId'], $clientUid);
            // 获取被保人名字
            $policyContent['userName'] = $familyPolicy['userName'];
            //通过保单号获取mongo数据
            $policyCont =  $this -> getPolicyInfoById($contactsPolicyIds);
            if($policyCont['status'] != 1){
                PublicMethod::log(__FUNCTION__, $policyCont['msg']);
                continue;
            }
            $policyContent['Liabilitys'] = $policyCont['info'];
            $familyPolicyInfo[] = $policyContent;
        }
        // 获取大责任（版本）
        $projectLiabilityInfo = $this -> getProjectLiabilityInfo();

        if($projectLiabilityInfo['status'] != 1){
            $this -> debug($projectLiabilityInfo['msg']);
        }
        //转码json
        $familyPolicyInfo = json_encode($familyPolicyInfo);
        //获取分页数据
        $pageShow = $this->getPages($familyPolicyList['info']['count'], $limitLength);
        //分配分页数据
        $this -> assign('pageShow', $pageShow);
        //分配怎人版本关系
        $this -> assign('projectLiabilityInfo', $projectLiabilityInfo['info']);
        //分配用户信息
        $this -> assign('familyPolicyInfo', $familyPolicyInfo);
        $this -> display(__FUNCTION__);
    }


    // //保单详情页
    // public function myPolicyDetail(){
    //     //获取保单号
    //     $policyId = I('policyId', '', 'htmlspecialchars,trim');
    //     if(empty($policyId)){
    //         $this -> debug('ServerError -> 无法获取保单号');
    //     }
    //     $responsePolicyInfo = $this -> getPolicyInfo($policyId);
    //     if(!$responsePolicyInfo){
    //         $this -> debug('ServerError -> 获取保单详情信息失败！');
    //     }
    //     if(empty($responsePolicyInfo)){
    //         $this -> debug('ServerError -> 保单信息不存在！');
    //     }
    //     $this -> assign('policyInfo', $responsePolicyInfo);
    //     $this -> display(__FUNCTION__);
    // }


    //添加新用户(ajax)
    public function addNewUser(){
        //获取请求数据
        $clientName = I('inputName', '', 'htmlspecialchars,trim');
        $clientNameLen = mb_strlen($clientName, 'utf-8');
        if($clientNameLen > 40){
            $this -> jsonResponse(array('status' => 2, 'msg' => '输入姓名格式有误'));
        }
        $userTel = I('inputTel', '', 'htmlspecialchars,trim');
        if(!$clientName ||!$userTel){
            $this -> jsonResponse(array('status' => 3, 'msg' => '请完善您的数据'));
        }
        //引入校验手机号类
        import('Common.Tool.DataCheck', APP_PATH, '.php');
        if(!DataCheck::isMobile($userTel)){
            $this -> jsonResponse(array('status' => 4, 'msg' => '手机号格式不正确'));
        }
        //获取用户Uid
        $uid = $this -> getUid();
        $requestData = array(
            'uid' => $uid,
            'clientName' => $clientName,
            'mobile' => $userTel
        );
        $addStatus = Communication::request('enterpriseApi', '/Api/JunKangEnterprise/createNewClient', $requestData);
        if ($addStatus['status'] == 10006) {
            $this -> jsonResponse(array('status' => 5, 'msg' => '您已添加过该用户！'));
        } else if ($addStatus['status'] == 10015){
            $this -> jsonResponse(array('status' => 6, 'msg' => '您的无保单用户已达到上限(上限人数为20位),请先添加保单！'));
        } else if($addStatus['status'] != 1) {
            $this -> jsonResponse(array('status' => 7, 'msg' => '添加新用户失败！'));
        }
        //先发送模版消息然后
        $messageData = array('userName' => $clientName);
        $sendRes = $this -> sendShortMessage($uid, 5, $messageData);
        if($sendRes['status'] != 1){
            PublicMethod::log(__FUNCTION__, '发送模版消息失败' . $sendRes);
        }
        $this -> jsonResponse(array('status' => 1, 'msg' => '添加新用户成功！'));
    }


    //用于解密用户的uid
    private function userIdDecrypt($encryptUid){
        if(!$encryptUid){
            $this -> debug('ServerError -> 获取加密uid失败！');
        }
        //拆分数据获取uid
        list($encryptTemp, $encryptUid, $encryptKey) = explode('_', $encryptUid);
        //解密uid
        list($temp, $uid) = PublicMethod::numberBetweenDecrypt($encryptTemp, $encryptUid, $encryptKey);
        if(!$uid){
            $this -> debug('ServerError -> 获取uid失败！');
        }
        return $uid;
    }


    //获取代理人的用户（有保单）
    private function getUserListHasPolicy($requestData=array()){
        $usesInfo = Communication::request('enterpriseApi', '/Api/JunKangEnterprise/queryPolicyClientList', $requestData);
        if ($usesInfo['status'] != 1) {
            $this->debug('ServerError -> ' . $response['status'] . '获取用户信息失败（有保单）！');
        }else if(empty($usesInfo['info']['info'])){
           return false;
        }
        //返回有数据的用户列表
        return $usesInfo['info'];
    }

    //获取代理人的用户（没有保单）
    private function getUserListNoPolicy($uid){
        $usesInfo = Communication::request('enterpriseApi', '/Api/JunKangEnterprise/queryNoPolicyClient', array('uid'=>$uid));
        if ($usesInfo['status'] != 1) {
            $this->debug('ServerError -> ' . $response['status'] . '获取用户信息失败（无保单）！');
        }else if(empty($usesInfo['info'])){
           return false;
        }
        //返回有数据的用户列表
        return $usesInfo['info'];
    }

    //获取客户的家庭详情
    private function getFamilyPolicyList($requestData=array()){
        $familyPolicyList = Communication::request('enterpriseApi', '/Api/JunKangEnterprise/queryClientFamilyList',  $requestData);
        //返回客户家庭保单信息
        return $familyPolicyList;
    }


    //获取家庭保单详情(小图片)
    private function getClientPolicyInfo($requestData=array()){
        $familyPolicyInfo = Communication::request('enterpriseApi', '/Api/JunKangEnterprise/getClientPolicyInfo',  $requestData);
        //返回客户家庭保单信息
        return $familyPolicyInfo;
    }


    //获取被保人保单详情列表
    private function getContactsIdPolicyInfo($requestData=array()){
        $contactsIdPolicyInfo = Communication::request('enterpriseApi', '/Api/JunKangEnterprise/getInsuredPolicyInfo', $requestData);
        //返回客户家庭保单信息
        return $contactsIdPolicyInfo;
    }

    //获取当前代理人和当前客户的保单号信息
    private function getPolicyIds($requestData=array()){
        $policyIds = Communication::request('enterpriseApi','/Api/JunKangEnterprise/getClientPolicyNumberInfo', $requestData);
        if($policyIds['status'] != 1){
            return false;
        }
        return $policyIds['info'];
    }


    // //通过保单号获取保单详情
    // private function getPolicyInfo($policyId){
    //     //请求数据
    //     $communicationKey = C('POLICY.communicationKey');
    //     $requestData = array('communicationKey' => $communicationKey, 'policyId' => $policyId);
    //     $policInfo = Communication::request('sourcePolicy', '/Api/Policy/queryPolicyInfoByPolicyId', $requestData);
    //     if($policInfo['status'] != 1 ){
    //        return false;
    //     }
    //     return json_encode($policInfo['info'][0]['Mongo_data']);
    // }


    //添加用户消息通知
    private function sendShortMessage($uid, $messageTemplateId, $messageData){
        $requestData = array('uid' => $uid, 'messageTemplateId' => $messageTemplateId, 'messageData' => $messageData);
        $sendStatus = Communication::request('enterpriseApi', '/Api/JunKangEnterprise/addMessageTemplateInfo', $requestData);
        return $sendStatus;
    }


     //获取模版推送消息
    private function getShortMessageList($uid){
        //获取请求数据
        $requestData = array('uid' => $uid);
        $messageList = Communication::request('enterpriseApi', '/Api/JunKangEnterprise/pushMessageInfo', $requestData);
        if ($messageList['status'] != 1) {
            return false;
        }
        foreach ($messageList['info']['info'] as  &$message) {
            //获取json信息
            $messageInfo = json_decode($message['pushMessageData'], true);
            $message['policyId'] = isset($messageInfo['policyId']) ? $messageInfo['policyId']: '';
            $message['encryptUid'] = isset($messageInfo['encryptUid']) ? $messageInfo['encryptUid']: '';
        }
        return $messageList['info'];
    }

    //获取用户信息
    private function getUserInfo($uid){
        $userInfo = Communication::request('enterpriseApi', '/Api/JunKangEnterprise/getUserInfo', array('uid' => $uid));
        if($userInfo['status'] != 1){
            return false;
        }
        return $userInfo['info'];
    }


    //获取被保人信息
    private function getContactsInfo($contactsId){
        $contactsInfo = Communication::request('enterpriseApi', '/Api/JunKangEnterprise/getContactsInfo',array('contactsId' => $contactsId));
        if($contactsInfo['status'] != 1 ){
            return false;
        }
        return $contactsInfo['info'];
    }

    // 获取用户保单解析状态
    private function getPolicyStatus($requestData){
        $policyStatus = Communication::request('api', '/Api/BaoShiTong/policyAnalysisStatus', $requestData);
        if($policyStatus['status'] != 1 ){
            return false;
        }
        return $policyStatus['info'];
    }

    //获取用户家庭保单信息
    private function getFamilyPolicyInfo($clientUid){
        $uid = $this -> getUid();
        $requestData = array('uid' => $uid, 'clientUid' => $clientUid);
        $familyPolicyInfo = Communication::request('enterpriseApi', '/Api/JunKangEnterprise/handleFamilyAnalysis', $requestData);
        if($familyPolicyInfo['status'] != 1){
            return false;
        }
        return $familyPolicyInfo['info'];
    }

    //解析被保人保单信息
    private function getAnalysisInfo($clientUid, $contactsId){
        $uid = $this -> getUid();
        $requestData = array('uid' => $uid, 'clientUid' => $clientUid, 'contactsId' => $contactsId);
        $analysisInfo = Communication::request('enterpriseApi', '/Api/JunKangEnterprise/getInsuredAnalysisInfo', $requestData);
        if($analysisInfo['status'] != 1){
            return false;
        }
        return $analysisInfo['info'];
    }

    //获取图片链接
    private function getImgUrl($bigImgUrl=array()){
        //获取url路径信息
        $policyConf = C('POLICY');
        $bigImgUrlPath = str_replace('./', '/', $policyConf['policyOriginal']);
        //获取缩略图路径
        $thumpImgUrlPath = str_replace('./', '/', $policyConf['policyThumb']);
        if (!$bigImgUrlPath || !$thumpImgUrlPath) {
           return false;
        }
        //存放图片路径的空数组
        $urlTemp = array();
        foreach ($bigImgUrl as $imgurl) {
            //获取图片名字
            $bigImageUrl = parse_url($imgurl);
            $fileName = basename($bigImageUrl['path']);
            $policyStatus = array(
                'thumbImg' => $thumpImgUrlPath  . $fileName,
                'OriginalImg' => $bigImgUrlPath . $fileName
            );
            $urlTemp[] = $policyStatus;
        }
        return $urlTemp;
    }


   //  认证登陆
    private function certifiedLanding()
    {
        //  由认证登陆时候产生的
        $token = I('token', '' ,'htmlspecialchars,trim');
        if(!$token)    
        {
            //  判断是否有session
            $loginUid = $this->getUid();
            if($loginUid)  //  如果已经登陆了就不需要做验证了
            { 
                return '';
            }   
        }
        //  引入用于网页认证类
        import('Common.CloudCertification.webAuthorize', APP_PATH, '.php');
        //  实例化网页认证类
        $webAuthorize = new webAuthorize();
        $uid = $webAuthorize->getUid($token);
        if($uid)
        {
            $this->setLogin($uid);
            return '';
        }else
        {
            //  判断是否有session
            $loginUid = $this->getUid();
            if($loginUid)  //  如果已经登陆了就不需要做验证了
            { 
                return '';
            }   
            // $this -> debug('用户来源错误!');
            $this -> jsonResponse(array('status' => 10009, 'msg' => '用户来源错误'));             
        }
    }



    //分页类
    private function getPages($count,$limitLeng){
        //分页类
        import('ORG.Util.Page');
        $page = new Page($count,$limitLeng);
        $page->setConfig('prev', '上一页');//上一页
        $page->setConfig('theme', '%upPage%');//只显示上下页选项
        $pre = $page->show();
        $page->setConfig('next', '下一页');//下一页
        $page->setConfig('theme', '%downPage%');//只显示上下页选项
        $next = $page->show();
        //分页显示数据
        if(empty($pre) && empty($next)){
            $pre = '';
            $next = '';
        }else{
            if(empty($pre)){
                $pre="javascript:void(0);";
                $pre = "<a href ='".$pre."'>当前页</a>";
            }
               if(empty($next)){
                $next="javascript:void(0);";
                $next = "<a href ='".$next."'>当前页</a>";
            }
        }
        $page_show[] = $pre;
        $page_show[] = $next;
        return $page_show;
    }

    //  拼接接口需要的图片地址
    private function imgPath($imgPath)
    {
        $imgPath = str_replace('./','/',$imgPath);
        $policImg = URL_JUNKANG.$imgPath;
        return $policImg;
    }

    //  图片数量处理(并且创建需要的文件夹)
    private function morethanPics()
    {
        //  获取上传的图片信息
        $img64Base = $_POST['img64base'];
        //  获取图片上传的张数
        $imgLength = count($img64Base);
        if($imgLength < 1)
        {
            $this -> jsonResponse(array('status' => 9, 'msg' => '至少上传一张图片'));
        }elseif($imgLength > 2)
        {
            $this -> jsonResponse(array('status' => 8, 'msg' => '上传图片不能多于两张'));            
        }
        //  图片数量判断通过之后，创建文件夹用于保存图片
        //  首先需要创建文件夹(递归创建缩略图文件夹的同时会生成policyanalysis文件夹)
        $thumbPath = C('POLICY.policyThumb');
        $originalPath = C('POLICY.policyOriginal');
        //  判断路径存不存在，不存在就创建
        PublicMethod::createDirectory($thumbPath);
        PublicMethod::createDirectory($originalPath);
    }

    //  提示错误信息
    private function errorMessage($errorMsg){
        $data = URL_JUNKANG . '/YunBaoDan/uploadPolicyImg?errormsg='.$errorMsg;
        //  跳转回上传页面
        $this->gotoUrl($data);
        exit;
    }

    //获取保单的信息（通过保单号数组）
    private function getPolicyContent($policyIds){
        //为保单号去重
        array_unique($policyIds);
        //要查询的字段
        $queryField = array('BInsured', 'Name', 'SecurityMoney', 'Liabilitys.shortName', 'BXGSid', 'menuCon.paymentInformation.payPeriod', 'menuCon.paymentInformation.CostPrice','StartDate','EndDate');
        $communicationKey = C('POLICY.communicationKey');
        if(!$communicationKey){
            return array('status' => 2, 'msg' => '获取communicationKey失败');
        }
        $requestData = array('queryField' => $queryField, 'communicationKey' => $communicationKey, 'policyIdList' => $policyIds);
        $policyContent = Communication::request('sourcePolicy', '/Api/Policy/queryAllPolicyInfo', $requestData);
        if($policyContent['status'] != 1){
            return array('status' => 3, 'msg' => '获取保单信息失败！' . $policyContent['status']);
        }
        if(empty($policyContent['info'])){
            return array('status' => 4, 'msg' => '获取保单信息不存在！');
        }
        //要返回的数据
        $policyInfoArr = array();
        foreach ($policyContent['info'] as $policyInfo) {
            //存放临时保单信息数组
            $policyCont = array();
            // 获取包含需要字段的数组
            $policy = $policyInfo['Mongo_data'];
            //获取被保人
            $policyCont['beneficiary'] = isset($policy['BInsured']) ? $policy['BInsured'] : '';
            // 标题
            $policyCont['title'] = isset($policy['Name']) ? $policy['Name'] : '';
            //保额
            $policyCont['SecurityMoney'] = isset($policy['SecurityMoney']) ? $policy['SecurityMoney']/10000 : '';
            //保单号
            $policyCont['policyId'] = isset($policy['BXGSid']) ? $policy['BXGSid'] : '';
            //责任名字
            $policyCont['responsibilityName'] = isset($policy['Liabilitys']) ? $policy['Liabilitys'] : array();
            //保险起始
            $policyCont['startDate'] = isset($policy['StartDate']) ? $policy['StartDate'] :'';
            //保险结束
            $policyCont['endDate'] = isset($policy['EndDate']) ? $policy['EndDate'] :'';
            //缴费期间
            $policyCont['payPeriod'] = isset($policy['menuCon']['paymentInformation']['payPeriod']) ? $policy['menuCon']['paymentInformation']['payPeriod'] : 0;
            //总保费
            $costPrice = isset($policy['menuCon']['paymentInformation']['CostPrice']) ? $policy['menuCon']['paymentInformation']['CostPrice'] : 0;
            //每年的平均保费
            $costPrice = floor($costPrice);
            $policyCont['averagePrice'] = substr(($costPrice), 0, 6);
            $policyInfoArr[] = $policyCont;
        }
        //保单排序
        usort($policyInfoArr, function($front,$next) use (&$policyIds){
            //数组中的前一个
            $frontVal = $front['policyId'];
            //数组中的后一个
            $nextVal = $next['policyId'];
            //是否要排序
            return (array_search($frontVal, $policyIds) < array_search($nextVal, $policyIds)) ? -1 : 1;
        });
        return array('status' => 1, 'msg' => '获取保单信息成功', 'info' => $policyInfoArr);
    }

    //添加图片上传记录
    private function addImageRecord($deAgentUid,$imagesUrl, $key,$baoshitongPlatformId,$checkKey){
        //  如果没有代理人ID
        if (!$baoshitongPlatformId) {
            // $this -> errorMessage('获取平台id失败！');
            $this -> jsonResponse(array('status' => 30, 'msg' => '获取平台id失败！'));               
        }
        //  如果没有checkkey
        if (empty($checkKey)) {
            // $this -> errorMessage('获取checkKey失败！');
            $this -> jsonResponse(array('status' => 31, 'msg' => '获取checkKey失败！'));             
        }
        $requestData = array(
            'uid' => $deAgentUid, 
            'imageUrl' => $imagesUrl, 
            'key' => $key, 
            'checkKey' => $checkKey,
            'baoshitongPlatformId' => $baoshitongPlatformId
        );
        $responseStatus = Communication::request('policyApi', '/Api/BaoShiTongExternal/addImageUploadRecord', $requestData);
        if($responseStatus['status'] != 1){
            $this -> jsonResponse(array('status' => 32, 'msg' => '添加图片上传记录失败！'));              
            // $this -> errorMessage('添加图片上传记录失败！');
        }
    }



    //获取方案责任信息
    private function getProjectLiabilityInfo(){
        // 保存路径地址
        $path = './File/responsibilityVersion/';
        //保存version
        PublicMethod::createDirectory($path);
        if(!file_exists($path . 'version.json')){
            $version = -1;
            $projectLiabilityInfo = $this -> getProjectLiability($version);
            if(!$projectLiabilityInfo){
                $this -> debug('ServerError -> 获取责任信息不存在!');
            }
            if($projectLiabilityInfo['info']['status'] == 1){
                //保存version
                // PublicMethod::createDirectory($path);
                //保存责任信息json
                $versionNum = array('version' => $projectLiabilityInfo['info']['version']);
                $versionNum = json_encode($versionNum);
                $res = file_put_contents($path . 'version.json' , $versionNum);
                $projectLiabilityInfo = json_encode($projectLiabilityInfo);
                $resInfo = file_put_contents($path . 'versionInfo.json' , $projectLiabilityInfo);
                if(!$res || !$resInfo){
                    PublicMethod::log(__FUNCTION__, '保存责任版本失败');
                }

                return array('status' => 1, 'msg' => '获取责任信息成功','info' => json_encode($projectLiabilityInfo));
            } 
            // $this->jsonResponse(array('statusInfo'=>2));
            return array('status'=> 2,'msg'=>'保存责任版本失败');
            // return false;
        }else{
            //获取文件名字
            $versionNum = file_get_contents($path . 'version.json');
            $versionNum = json_decode($versionNum,true);
            $version = $versionNum['version'];
            //获取大责任
            $projectLiability = $this -> getProjectLiability($version);
            if(!$projectLiability){
                $this -> debug('ServerError -> 获取方案责任信息失败!');
            }
            if($projectLiability['info']['status'] == 1){
                //保存责任信息json
                $version = $projectLiability['info']['version'];
                $versionNum = array('version' => $version);
                $versionNum = json_encode($versionNum);
                $res = file_put_contents($path . 'version.json' , $versionNum);
                $versionInfo = json_encode($projectLiability);
                $resInfo = file_put_contents($path . 'versionInfo.json' , $versionInfo);
                if(!$res || !$resInfo){
                    PublicMethod::log(__FUNCTION__, '保存责任版本失败');
                }
                return array('status' => 1, 'msg' => '获取责任信息成功','info' => $versionInfo);
            }
            if($projectLiability['info']['status'] == 2){
                //返回文件数据
                $content = file_get_contents($path . 'versionInfo.json');
                return array('status' => 1, 'msg' => '获取责任信息成功','info' => $content);
            }
            return array('status'=>3,'msg'=>'无法获取责任版本');
        }

    }


    // 获取方案责任
    private function getProjectLiability($version){
        // 获取君康Uid
        $adminInfo = $this -> getAdminUid();
        if($adminInfo['status'] != 1){
            $this -> debug('ServerError ->' . $adminInfo['msg']);
        }
        $cloudUid = $adminInfo['cloudUid'];
        $channelId = C('POLICY.defaultChannel');
        //获取account
        $account = $channelId[1];
        $channelId = $this -> getJunKangChannelId($account);
        $requestData = array('cloudUid' => $cloudUid, 'channelId' => $channelId, 'version' => $version);
        $projectLiabilityInfo = Communication::request('enterpriseApi', '/Api/JunKangProjectLiability/getProjectLiabilityInfo', $requestData);
        if($projectLiabilityInfo['status'] != 1){
            return false;
        }

        return $projectLiabilityInfo;
    }

    //获取均康uid
    private  function getAdminUid(){
        $loginAccount = C('POLICY.BackstageAccountNumber');
        $adminInfo = Communication::request('enterpriseApi', '/Api/JunKangAdmin/getAdminUid', array('loginAccount' => $loginAccount));
        if($adminInfo['status'] != 1){
            return array('status' => 2, 'msg' => '获取后台uid失败' . $adminInfo['status']);
        }
        return array('status' => 1, 'msg' => '获取后台uid成功', 'cloudUid' => $adminInfo['cloudUid']);
    }

     // 用户责任合并
    private function consolidationResponsibility($responsibility)
    {
        //  结果责任
        $resultResponsibility = array();
        foreach ($responsibility as $key => $value) {
            if (array_key_exists($value['shortName'], $resultResponsibility)) {
                $shortName = $value['shortName'];
                $resultResponsibility[$shortName] = $resultResponsibility[$shortName]  + $value['SecurityMoney'];
            }else{
                $shortName = $value['shortName'];
                $resultResponsibility[$shortName] = $value['SecurityMoney'];
            }
        }
        $mergerResponsibility = array();
        foreach ($resultResponsibility as $key => $value) {
            $mergerResponsibility[] = array(
                'shortName'=>$key,
                'SecurityMoney'=>$value,
            );
        }
        return $mergerResponsibility;
    }

    //添加保单解析记录
    private function policyParsingRecord($deAgentUid, $key,$baoshitongPlatformId,$checkKey){
        //  如果没有代理人ID
        if (!$baoshitongPlatformId) {
            // $this -> errorMessage('获取平台id失败！');
            $this -> jsonResponse(array('status' => 33, 'msg' => '获取平台id失败！'));
        }
        //  如果没有checkkey
        if (empty($checkKey)) {
            // $this -> errorMessage('获取checkKey失败！');
            $this -> jsonResponse(array('status' => 34, 'msg' => '获取checkKey失败！'));
        }
        //  添加保单解析记录
        $requestData = array(
            'uid'      =>  $deAgentUid,
            'checkKey' =>  $checkKey,
            'key'      =>  $key,
            'baoshitongPlatformId' => $baoshitongPlatformId,
        );
        $response = Communication::request('policyApi', '/Api/BaoShiTongExternal/addPolicyAnalysis', $requestData);
        if($response['status'] != 1){
            // $this -> errorMessage('添加保单解析记录失败！');
            $this -> jsonResponse(array('status' => 35, 'msg' => '添加保单解析记录失败！'));
        }
    }
}

